package com.datawale.vh.demo.work.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {

    @Value("${file.store-dir}")
    private String storeDir;

    @PostMapping("/common/upload")
    public Map uploadFile(MultipartFile file) throws Exception{
        Map result = new HashMap();
        result.put("code", 0);
        if(file.isEmpty()){
           result.put("msg", "上传失败，请选择文件");
        }
        // 上传文件/图像到指定文件夹（这里可以改成你想存放地址的相对路径）
        File savePos = new File(storeDir);
        if(!savePos.exists()){  // 不存在，则创建该文件夹
            savePos.mkdir();
        }
        // 获取存放位置的规范路径
        String realPath = savePos.getCanonicalPath();
        String fileName = System.currentTimeMillis()+".png";
        String savePath=realPath+"/"+fileName;
        // 上传该文件/图像至该文件夹下
        file.transferTo(new File(savePath));
        result.put("fileName", fileName);
        result.put("url", savePath);
        result.put("imageUrl", "http://localhost:7003/common/download?fileName="+fileName);
        return result;
    }

    @PostMapping("/common/uploadAudio")
    public Map uploadAudio(@RequestBody MultipartFile file) throws Exception{
        Map result = new HashMap();
        result.put("code", 0);
        if(file.isEmpty()){
            result.put("msg", "上传失败，请选择文件");
            return result;
        }
        // 上传文件/图像到指定文件夹（这里可以改成你想存放地址的相对路径）
        File savePos = new File(storeDir);
        if(!savePos.exists()){  // 不存在，则创建该文件夹
            savePos.mkdir();
        }
        // 获取存放位置的规范路径
        String realPath = savePos.getCanonicalPath();
        String fileName = System.currentTimeMillis()+".wav";
        String savePath=realPath+"/"+fileName;
        // 上传该文件/图像至该文件夹下
        file.transferTo(new File(savePath));
        result.put("fileName", fileName);
        result.put("url", savePath);
        result.put("imageUrl", "http://localhost:7003/common/download?fileName="+fileName);
        return result;
    }

    @GetMapping("/common/download")
    public void downloadFile(String fileName, HttpServletResponse response) {
        //输入流，通过输入流读取文件内容
        try {
            File savePos = new File(storeDir);
            if(!savePos.exists()){  // 不存在，则返回错误信息
                return;
            }
            // 获取存放位置的规范路径
            String realPath = savePos.getCanonicalPath();
            String filePath=realPath+"/"+fileName;
            FileInputStream fileInputStream = new FileInputStream(new File(filePath));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
